package com.example.okhttp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author:0.2℃
 * @date： 2022-01-04 18:57
 * @version:
 * @Description ：准备了一个队列，有一个添加队列的一个方法，整了一个线程池
 */
public class ThreadPoolManager {

    private static ThreadPoolManager instance = new ThreadPoolManager();

    public static ThreadPoolManager getInstance() {
        return instance;
    }

    private static LinkedBlockingQueue<Runnable> mQueue = new LinkedBlockingQueue<>();

    public void addTask(Runnable runnable) {
        try {
            mQueue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private ThreadPoolExecutor mExecutor;

    private ThreadPoolManager (){
        TimeUnit unit;
        BlockingQueue workQueue;
        mExecutor = new ThreadPoolExecutor(3, 10, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(4),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
                        addTask(runnable);
                    }
                });
        mExecutor.execute(coreThread);
    }

    /**
     * 核心线程
     */
    public Runnable coreThread = new Runnable() {
        Runnable runn = null;
        @Override
        public void run() {
            while (true) {
                try {
                    runn = mQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mExecutor.execute(runn);
            }

        }
    };
}
